package com.spring.security.springsecuritydemo.config;


import com.spring.security.springsecuritydemo.handle.MyAccessDeniedHandler;
import com.spring.security.springsecuritydemo.handle.MyFailHandle;
import com.spring.security.springsecuritydemo.handle.MySuccessHandle;
import com.spring.security.springsecuritydemo.service.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder getPw(){
        return new BCryptPasswordEncoder();
    }

    @Autowired
    private MyAccessDeniedHandler myAccessDeniedHandler;

    @Autowired
    private UserDetailsServiceImpl userDetailsService;
    @Autowired
    private DataSource dataSource;

    @Autowired
    private PersistentTokenRepository persistentTokenRepository;
    /**
     * 自定义登录页面
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                //设置用户名与密码的别名
                .usernameParameter("username")
                .passwordParameter("password")
                //自定义登录页面
                .loginProcessingUrl("/login")
                .loginPage("/login.html")
                //成功后跳转
//                .successForwardUrl("/toMain")
                .successHandler(new MySuccessHandle("https://www.baidu.com"))
                //失败后跳转
//                .failureForwardUrl("/toFail");
                .failureHandler(new MyFailHandle("/fail.html"));
//        授权认证
        http.authorizeRequests()
                //失败页面匹配后放行
                .antMatchers("/fail.html").permitAll()
                //登录页面匹配后放行
                .antMatchers("/login.html").permitAll()
//                .anyRequest().authenticated();
                //自定义权限验证
                .anyRequest().access("@myServiceImpl.hasPermission(httpServletRequest,authentication)");

        //关闭cors
        http.csrf().disable();

        //处理403请求
        http.exceptionHandling().accessDeniedHandler(myAccessDeniedHandler);

        //记住我功能
        http.rememberMe()
                //失效时间60秒
                .tokenValiditySeconds(60)
                .userDetailsService(userDetailsService)
                .tokenRepository(persistentTokenRepository);
    }

    /**
     * rememberMe功能使用
     * @return
     */
    @Bean
    public PersistentTokenRepository  getPersistentTokenRepository(){
        JdbcTokenRepositoryImpl jdbcTokenRepository=new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);
        //创建相关的表，第一次启动时需要
        jdbcTokenRepository.setCreateTableOnStartup(true);

        return jdbcTokenRepository;
    }
}
